package cc.ttiot.thread.dataCollectionThread;

/*
 * ************************************************************************
 * ORGANIZATION  :  cc.ttiot
 * PROJECT       :  cc.ttiot :: ProtectiveDoor
 * FILENAME      :  VibrationThread.java
 *
 * This file is part of the ProtectiveDoor project. More information about
 * this project can be found here:  https://www.ttiot.cc
 * ************************************************************************
 */

import cc.ttiot.mapper.dao.VibrationMsgMapper;
import cc.ttiot.mapper.domain.VibrationMsg;
import cc.ttiot.mapper.utils.MybatisUtils;
import cc.ttiot.service.dataCollection.i2c.impl.VibrationCollection;
import cc.ttiot.utils.TimeUtils;
import com.pi4j.io.i2c.I2CDevice;
import org.apache.ibatis.session.SqlSession;
import java.io.IOException;

/**
 * @Description:
 * @Author :
 * @Version :
 * @Date :
 */
public class VibrationCollectThread implements Runnable {
    //数据库初始化
    /*
        1) SqlSession类是线程不安全的，所以每个线程都要有个单独的SqlSession
        2) 下面这种sqlSessionFactory.openSession()的方式获取SqlSession对象默认事务autoCommit设为false，
           所以除了查询语句其他语句执行后要调用sqlSession.commit()方法提交事务
     */
    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final VibrationMsgMapper vmMapper = sqlSession.getMapper(VibrationMsgMapper.class);
    private final VibrationMsg vibrationMsg = new VibrationMsg();

    private final I2CDevice device;

    public VibrationCollectThread(I2CDevice device) {
        this.device = device;
    }

    @Override
    public void run() {
        VibrationCollection vibrationCollection = VibrationCollection.getInstance();
        vibrationCollection.setI2CDevice(device);
        while(true){
            synchronized (device){
                try {
                    double vibration = vibrationCollection.collect();
//                    System.out.printf("振动速度 = %.2f mm/s\n", vibration);

                    if(vibration > 0.2){
                        //更新数据
                        vibrationMsg.setVibration(vibration);
                        vibrationMsg.setTime(TimeUtils.getMillisecondTime());

                        //存入数据库
                        vmMapper.insertSingle(vibrationMsg);
                        sqlSession.commit();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }


    }
}
